<template>
    <div class="card-body">
        <form @submit.prevent="applyFilter" class="row g-3 align-items-end">
            <!-- 1. 日期类型选择（修改为年月选择） -->
            <div class="col-6 col-md-3">
                <select v-model="selectedMonth" class="form-select" @change="onMonthSelect">
                    <option v-for="month in availableMonths" :key="month.value" :value="month.value">
                        {{ month.label }}
                    </option>
                </select>
            </div>

            <!-- 2. 分类选择 (使用 IconDropdown 组件) -->
            <div class="col-6 col-md-3">
                <IconDropdown v-model="categoryId" :options="categoriesWithIcons" :loading="categoryLoading"
                    placeholder="全部分类" @click="onCategoryClick" />
            </div>

            <!-- 3. 开始日期 -->
            <div class="col-6 col-md-3">
                <input type="date" v-model="startDate" class="form-control" @input="clearMonthSelection" />
            </div>

            <!-- 4. 结束日期 -->
            <div class="col-6 col-md-3">
                <input type="date" v-model="endDate" class="form-control" @input="clearMonthSelection" />
            </div>

            <!-- 操作按钮-->
            <div class="col-6 col-md-3">
                <button type="submit" class="btn btn-primary w-100">✅ 筛选</button>
            </div>
            <div class="col-6 col-md-3">
                <button type="button" class="btn btn-outline-secondary w-100" @click="resetFilter">
                    ♻️ 重置
                </button>
            </div>
        </form>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useApi } from '../composables/useApi';
import IconDropdown from './IconDropdown.vue'; // 导入 IconDropdown 组件

const emit = defineEmits(['filter']);

// ===== 筛选数据 =====
const selectedMonth = ref('');
const startDate = ref('');
const endDate = ref('');
const categoryId = ref('');

// ===== 生成年月选项 =====
const availableMonths = computed(() => {
    const months = [];
    const now = new Date();

    // 生成最近24个月的选项
    for (let i = 0; i < 12; i++) {
        const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const label = `${year}年${month}月`;
        const value = `${year}-${month.toString().padStart(2, '0')}`;

        months.push({
            label,
            value
        });
    }

    return months;
});

// 设置默认月份为当前月份
const setDefaultMonth = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    selectedMonth.value = `${year}-${month}`;
    onMonthSelect(); // 触发月份选择事件来设置开始和结束日期
    // applyFilter(); // 主动触发一次筛选，确保默认日期参数被发送
};

// ===== 分类相关状态 =====
const categories = ref([]);
const categoryLoaded = ref(false);
const categoryLoading = ref(false);

// 为分类添加图标信息
const categoriesWithIcons = computed(() => {
    return categories.value.map(cat => ({
        id: cat.id,
        name: cat.name,
        icon: cat.icon || 'bi-tag', // 使用分类自身的图标，如果没有则使用默认图标
        color: cat.color || 'text-primary' // 使用分类自身的颜色，如果没有则使用默认颜色
    }));
});

// 点击分类下拉框时加载分类数据
const onCategoryClick = async () => {
    if (categoryLoaded.value) return;
    categoryLoading.value = true;

    const { result, fetchData } = useApi({
        url: '/transactions/search/category',
        method: 'GET',
        manual: true,
        transform: res => res.data || []
    });

    try {
        await fetchData();
        categories.value = result.value || [];
        categoryLoaded.value = true;
    } catch (e) {
        error('加载分类失败');
        console.warn('加载分类失败：', e);
    } finally {
        categoryLoading.value = false;
    }
};

// 选择年月时设置开始和结束日期
const onMonthSelect = () => {
    if (selectedMonth.value) {
        const [year, month] = selectedMonth.value.split('-').map(Number);

        // 设置开始日期为该月的第一天
        startDate.value = `${year}-${month.toString().padStart(2, '0')}-01`;

        // 设置结束日期为该月的最后一天
        const lastDay = new Date(year, month, 0).getDate();
        endDate.value = `${year}-${month.toString().padStart(2, '0')}-${lastDay}`;
    } else {
        // 清空日期
        startDate.value = '';
        endDate.value = '';
    }
};

// 清空月份选择
const clearMonthSelection = () => {
    selectedMonth.value = '';
};

// 应用筛选
const applyFilter = () => {
    // 确保空字符串也被传递，而不是被转换为undefined
    const filterData = {
        start_date: startDate.value,
        end_date: endDate.value,
        category_id: categoryId.value || undefined
    };

    // 移除空字符串字段
    Object.keys(filterData).forEach(key => {
        if (filterData[key] === '') {
            delete filterData[key];
        }
    });

    emit('filter', filterData);
};

// 重置筛选
const resetFilter = () => {
    selectedMonth.value = '';
    startDate.value = '';
    endDate.value = '';
    categoryId.value = '';
    setDefaultMonth(); // 设置默认月份并触发筛选
    applyFilter();
};

// 在组件挂载时设置默认月份
onMounted(() => {
    setDefaultMonth();
});

// Move defineExpose to the end of the script setup
// 添加defineExpose，暴露applyFilter方法
defineExpose({
    applyFilter
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>
